#include "inet.h"
#include "proc.h"
#include "game.h"

extern snake_t players[MAX_PLAYERS];
extern crd_t fruit;
extern init_mess_t init;

uint8_t is_alive[MAX_PLAYERS];
int sock;

void connect_to_server(const struct sockaddr_in *addr)
{
    printf("Connect to server %s ...\n", inet_ntoa(addr->sin_addr));

    memset(is_alive, 1, MAX_PLAYERS);
    sock = Socket(AF_INET, SOCK_STREAM, 0); 
    Connect(sock, (struct sockaddr *)addr, sizeof(struct sockaddr_in));
    
    printf("Connection is established !\n");

    Recv(sock, &init, sizeof(init_mess_t), 0);
    if (init.magic != 0x30)
    {
        fprintf(stderr, "Magic errror\n");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < init.n_players; ++i)
    {
        Recv(sock, players+i, 3, 0);
        Recv(sock, players[i].body, players[i].len*sizeof(crd_t), 0);
    }
}


void get_snakes()
{
    uint16_t num;
    uint16_t num_snakes;

    Recv(sock, &num_snakes, 2, 0);
    for (int i = 0; i < num_snakes; ++i)
    {
        Recv(sock, &num, 2, 0);
        draw_snake(' ', num);
        Recv(sock, players+num, 3, 0);
        Recv(sock, players[num].body, players[num].len*sizeof(crd_t), 0);
        is_alive[num] += 1;
    }

    for (int i = 0; i < init.n_players; ++i)
    {
        if (is_alive[i] == 0) continue;
        if (is_alive[i] - 1 == 0)
        {
            draw_snake(' ', i);
        }

        is_alive[i] -= 1;
    }
}


void is_dead()
{
    uint16_t place;
    Recv(sock, &place, 2, 0);
    close(sock);

    clear();
    wprintw(stdscr, "Your place is %hd !\n", place);
    refresh();
    exit(EXIT_SUCCESS);
}


void get_fruit()
{
    Recv(sock, &fruit, sizeof(crd_t), 0);
    mvaddch(fruit.y, fruit.x, FRUIT_CHAR);
}


void get_object()
{
    uint8_t magic;

    Recv(sock, &magic, 1, 0);
    if (magic == 0x50)
        get_snakes();
    else if (magic == 0xff)
        is_dead();
    else if (magic == 0xb0)
        get_fruit();
}
